<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>multiple</title>
</head>
<button id="download1">串行下载</button>
<button id="download2">多线程下载</button>

<body>
    <script src="https://cdn.bootcss.com/axios/0.19.2/axios.min.js"></script>
    <script>
        download1.onclick = () => {
            // console.time("直接下载");
            function download(url) {
                const req = new XMLHttpRequest();
                req.open("GET", url, true);
                req.responseType = "blob";
                req.onload = function (oEvent) {
                    const content = req.response;
                    const aTag = document.createElement('a');
                    aTag.download = '360_0388.jpg';
                    const blob = new Blob([content])
                    const blobUrl = URL.createObjectURL(blob);
                    aTag.href = blobUrl;
                    aTag.click();
                    URL.revokeObjectURL(blob);
                    // console.timeEnd("直接下载");
                };
                req.send();
            }
            download(url);
        }
        // buffer 合并 https://stackoverflow.com/questions/39502374/javascript-combine-arraybuffer-parts
        // https://louiswt.github.io/2019/06/10/browser-binary/
        function downloadRange(url, start, end, i) {
             return new Promise((resolve, reject) => {
                // const req = new XMLHttpRequest();
                // req.open("GET", url, true);
                // req.setRequestHeader('range', `bytes=${start}-${end}`)
                // req.responseType = "blob";
                // req.onload = function (oEvent) {
                //     req.response.arrayBuffer().then(res => {
                //         console.log(res,7410000);
                //         resolve({
                //             i,
                //             buffer: res
                //         });
                //     })
                // };
                // req.send();
                axios({
                    url,
                    method: 'get',
                    headers:{
                        range:`bytes=${start}-${end}`
                    },
                    responseType: 'arraybuffer'
                }).then((res) => {
                    console.log(res.data,6321000000000);
                    resolve({
                        i,
                        buffer: res.data
                    })
                }).catch((err) => {
                    reject(err)
                })
            })

        }
        // 合并buffer
        function concatenate(resultConstructor, arrays) {
            let totalLength = 0;
            for (let arr of arrays) {
                totalLength += arr.length;
            }
            let result = new resultConstructor(totalLength);
            let offset = 0;
            for (let arr of arrays) {
                result.set(arr, offset);
                offset += arr.length;
            }
            return result;
        }
        // const m = 1024 * 400;
        // const m = 1024 * 700
        const m = 1024 * 700;
        const url = 'http://127.0.0.1:8888/api/rangeFile?filename=360_0388.jpg';
        // const url = 'https://limit.qiufeng.com/static/360_0388.jpg';
        // const url = 'https://limit.qiufeng.com/static/360_0388.jpg';

        download2.onclick = () => {
            axios({
                url,
                method: 'head',
            }).then((res) => {
                // 获取长度来进行分割块
                console.time("并发下载");
                const size = Number(res.headers['content-length']);
                while (file.loadSize <size) {

                }
                console.log(size,7410000);
                const length = parseInt(size / m);
                const arr = []
                for (let i = 0; i <= length; i++) {
                    let start = i * m;
                    let end = (i == length) ? size - 1 : (i + 1) * m - 1;
                    arr.push(downloadRange(url, start, end, i))
                }
                Promise.all(arr).then(res => {
                    // console.time('合并数据');
                    const arrBufferList = res.sort(item => item.i - item.i).map(item => new Uint8Array(item.buffer));
                    const allBuffer = concatenate(Uint8Array, arrBufferList);
                    const blob = new Blob([allBuffer], { type: 'image/jpeg' });
                    const blobUrl = URL.createObjectURL(blob);
                    const aTag = document.createElement('a');
                    aTag.download = '360_0388.jpg';
                    aTag.href = blobUrl;
                    aTag.click();
                    URL.revokeObjectURL(blob);
                    // console.timeEnd('合并数据');
                    console.timeEnd("并发下载");
                })
            })
        }

    </script>
</body>

</html>
